"""
邮件消息数据模型
"""

from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, ForeignKey, Enum as SQLEnum
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
import enum

from app.core.database import Base


class EmailStatus(enum.Enum):
    """邮件状态枚举"""
    PENDING = "pending"      # 待发送
    SENDING = "sending"      # 发送中
    SENT = "sent"           # 已发送
    FAILED = "failed"       # 发送失败
    DELIVERED = "delivered"  # 已送达
    READ = "read"           # 已读


class EmailType(enum.Enum):
    """邮件类型枚举"""
    USER_MESSAGE = "user_message"        # 用户消息
    NOTIFICATION = "notification"        # 系统通知
    WELCOME = "welcome"                  # 欢迎邮件
    PASSWORD_RESET = "password_reset"    # 密码重置
    VERIFICATION = "verification"        # 邮箱验证
    SYSTEM_ALERT = "system_alert"       # 系统警告


class EmailPriority(enum.Enum):
    """邮件优先级枚举"""
    LOW = 1
    NORMAL = 2
    HIGH = 3
    URGENT = 4


class EmailMessage(Base):
    """邮件消息模型"""
    __tablename__ = "email_messages"

    id = Column(Integer, primary_key=True, index=True)
    
    # 发送者信息
    sender_id = Column(Integer, ForeignKey("users.id"), nullable=True)  # 系统邮件可以为空
    sender_email = Column(String(255), nullable=False)
    sender_name = Column(String(100))
    
    # 接收者信息
    recipient_id = Column(Integer, ForeignKey("users.id"), nullable=True)
    recipient_email = Column(String(255), nullable=False)
    recipient_name = Column(String(100))
    
    # 邮件内容
    subject = Column(String(500), nullable=False)
    body_text = Column(Text)  # 纯文本内容
    body_html = Column(Text)  # HTML内容
    
    # 邮件属性
    email_type = Column(SQLEnum(EmailType), default=EmailType.USER_MESSAGE)
    priority = Column(SQLEnum(EmailPriority), default=EmailPriority.NORMAL)
    status = Column(SQLEnum(EmailStatus), default=EmailStatus.PENDING)
    
    # 模板信息
    template_name = Column(String(100))
    template_data = Column(Text)  # JSON格式的模板数据
    
    # 发送信息
    sent_at = Column(DateTime(timezone=True))
    delivered_at = Column(DateTime(timezone=True))
    read_at = Column(DateTime(timezone=True))
    failed_reason = Column(Text)
    retry_count = Column(Integer, default=0)
    max_retries = Column(Integer, default=3)
    
    # 审计字段
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关联关系 (使用延迟绑定避免循环导入)
    sender = relationship("User", foreign_keys=[sender_id], back_populates="sent_emails", lazy="select")
    recipient = relationship("User", foreign_keys=[recipient_id], back_populates="received_emails", lazy="select")
    
    def __repr__(self):
        return f"<EmailMessage(id={self.id}, subject='{self.subject}', status='{self.status.value}')>"
    
    @property
    def is_system_email(self) -> bool:
        """是否为系统邮件"""
        return self.sender_id is None
    
    @property
    def can_retry(self) -> bool:
        """是否可以重试发送"""
        return (
            self.status == EmailStatus.FAILED and 
            self.retry_count < self.max_retries
        )


class EmailTemplate(Base):
    """邮件模板模型"""
    __tablename__ = "email_templates"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), unique=True, nullable=False, index=True)
    display_name = Column(String(200), nullable=False)
    description = Column(Text)
    
    # 模板内容
    subject_template = Column(String(500), nullable=False)
    body_template = Column(Text, nullable=False)
    
    # 模板属性
    email_type = Column(SQLEnum(EmailType), nullable=False)
    is_active = Column(Boolean, default=True)
    is_system = Column(Boolean, default=False)  # 是否为系统模板
    
    # 模板变量说明
    variables = Column(Text)  # JSON格式，描述模板变量
    
    # 审计字段
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    def __repr__(self):
        return f"<EmailTemplate(id={self.id}, name='{self.name}')>"


class EmailQueue(Base):
    """邮件队列模型（用于批量发送）"""
    __tablename__ = "email_queue"

    id = Column(Integer, primary_key=True, index=True)
    
    # 队列信息
    queue_name = Column(String(100), nullable=False, index=True)
    batch_id = Column(String(100), index=True)  # 批次ID
    
    # 邮件信息
    email_message_id = Column(Integer, ForeignKey("email_messages.id"), nullable=False)
    
    # 调度信息
    scheduled_at = Column(DateTime(timezone=True))  # 计划发送时间
    processed_at = Column(DateTime(timezone=True))
    
    # 状态
    status = Column(SQLEnum(EmailStatus), default=EmailStatus.PENDING)
    
    # 审计字段
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关联关系
    email_message = relationship("EmailMessage", foreign_keys=[email_message_id])
    
    def __repr__(self):
        return f"<EmailQueue(id={self.id}, queue='{self.queue_name}', status='{self.status.value}')>"